<template>
  <div>
    <h-table-list
      border
      type="local"
      :data="system_field.records"
      :columns="columns"
      :show-pagination="false"
      :form-options="formOptions"
    >
      <!-- <ListOpearteButton /> -->
      <template
        slot="slot-fieldName"
        slot-scope="scope"
      >
        <span v-if="scope.$index < 12">{{ scope.row.fieldName }}</span>
        <el-input
          v-if="scope.$index > 11"
          :ref="system_field.records[scope.$index].fieldName"
          v-model="system_field.records[scope.$index].fieldName"
          placeholder="请输入内容"
          :class="{ 'input-selected': false }"
        />
      </template>
      <template
        slot="slot-fieldType"
        slot-scope="scope"
      >
        <span v-if="scope.$index < 12">-</span>
        <el-select
          v-if="scope.$index > 11"
          :ref="system_field.records[scope.$index].fieldType"
          v-model="system_field.records[scope.$index].fieldType"
          placeholder="请选择"
        >
          <el-option
            v-for="item in selectOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </template>
      <template
        slot="slot-fieldRuleType"
        slot-scope="scope"
      >
        <span v-if="scope.$index < 12">-</span>
        <!--根据字段类型的动态变化字段规则字段模式,虽然功能很鸡肋-0- -->
        <!--单行纯数字（整数\小数）长度-->
        <el-input
          v-if="
            scope.$index > 11 &&
              system_field.records[scope.$index].fieldType != 'input' &&
              system_field.records[scope.$index].fieldType != 'select' &&
              system_field.records[scope.$index].fieldType != 'date' &&
              system_field.records[scope.$index].fieldType != 'organization'
          "
          :ref="system_field.records[scope.$index].fieldRuleType"
          v-model="system_field.records[scope.$index].fieldRuleType"
          type="number"
          placeholder="请输入内容"
          oninput="if(value>10) {return value=10} if(value<0){return value=-value} if(value==0){return value=null}"
        >
          <template slot="prepend">长度
          </template>
          <template slot="append">位</template>
        </el-input>
        <!--组织架构选择框-->
        <span v-if="
            scope.$index > 11 &&
              system_field.records[scope.$index].fieldType == 'organization'">-
        </span>

        <!--单行文本框长度-->
        <el-input
          v-if="
            scope.$index > 11 &&
              system_field.records[scope.$index].fieldType == 'input'
          "
          :ref="system_field.records[scope.$index].fieldRuleType"
          v-model="system_field.records[scope.$index].fieldRuleType"
          type="number"
          placeholder="请输入内容"
          oninput="if(value>100) {return value=100} if(value<0){return value=-value} if(value==0){return value=null}"
        >
          <template slot="prepend">长度
          </template>
          <template slot="append">位</template>
        </el-input>

        <!--时间选择-->
        <el-select
          v-if="
            scope.$index > 11 &&
              system_field.records[scope.$index].fieldType == 'date'
          "
          :ref="system_field.records[scope.$index].fieldType"
          v-model="system_field.records[scope.$index].fieldRuleType"
          placeholder="请选择"
        >
          <el-option
            v-for="item in selectDateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <el-input
          v-if="
            scope.$index > 11 &&
              system_field.records[scope.$index].fieldType == 'select'
          "
          :ref="system_field.records[scope.$index].fieldRuleType"
          v-model="system_field.records[scope.$index].fieldRuleType"
          placeholder="请输入内容"
          maxlength="100"
          minlength="1"
        />
      </template>
      <template
        slot="slot-description"
        slot-scope="scope"
      >
        <span v-if="scope.$index < 12">{{ scope.row.description }}</span>
        <el-input
          v-if="scope.$index > 11"
          :ref="system_field.records[scope.$index].description"
          v-model="system_field.records[scope.$index].description"
          placeholder="请输入内容"
          :class="{ 'input-selected': false }"
        />
      </template>
      <template
        slot="slot-required"
        slot-scope="scope"
      >
        <span v-if="scope.$index < 10">必填</span>
        <span v-if="scope.$index == 10">选填</span>
        <span v-if="scope.$index == 11">-</span>
        <el-select
          v-if="scope.$index > 11"
          :ref="system_field.records[scope.$index].required"
          v-model="system_field.records[scope.$index].required"
          placeholder="请选择"
        >
          <el-option
            :key="0"
            :label="'必填'"
            :value="0"
          />
          <el-option
            :key="1"
            :label="'选填'"
            :value="1"
          />
        </el-select>
      </template>

      <template
        slot="operate-column"
        slot-scope="scope"
      >
        <span v-if="scope.row.notFromInterface">-</span>
        <!-- <tableButton
          v-if="!scope.row.notFromInterface"
          :row="scope.row"
        /> -->
        <span v-if="!scope.row.notFromInterface">
          <el-button
            size="mini"
            @click="moveProTableData(scope.$index, scope.$index - 1)"
          >上移</el-button>
          <el-button
            size="mini"
            @click="moveProTableData(scope.$index, scope.$index + 1)"
          >下移</el-button>
          <el-button
            size="mini"
            @click="deleteProTableData(scope.row)"
          >删除</el-button>
        </span>
      </template>
    </h-table-list>

    <DownloadIdentify
      :visible.sync="dialogFormVisible"
      title="部门管理"
      @cancel="cancel"
      @update="dialogSubmit"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="姓名"
          prop="realName"
        >
          <el-input v-model="ruleForm.realName" />
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="phone"
        >
          <el-input v-model="ruleForm.phone" />
        </el-form-item>
        <el-form-item
          label="归属部门"
          prop="organId"
        >
          <el-input v-model="ruleForm.organId" />
        </el-form-item>
        <el-form-item
          label="职位"
          prop="positionsId"
        >
          <el-input v-model="ruleForm.positionsId" />
        </el-form-item>
        <el-form-item
          label="账号类别"
          prop="userType"
        >
          <el-input v-model="ruleForm.userType" />
        </el-form-item>
        <el-form-item
          label="登录账号"
          prop="userName"
        >
          <el-input v-model="ruleForm.userName" />
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input v-model="ruleForm.password" />
        </el-form-item>
      </el-form>
    </DownloadIdentify>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import waves from "@/directive/waves"; // waves directive
import DownloadIdentify from "@/components/FormDialog";
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import ListOpearteButton from "@/components/AllButton/button2";
import tableButton from "@/components/AllButton/button3";
import data from "./const";
import constData from "@/utils/constData";
export default {
  name: "Device",
  components: {
    DownloadIdentify,
    Pagination,
    tableButton,
    ListOpearteButton
  },
  directives: { waves },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    }
  },
  data() {
    return {
      selectOptions: [
        {
          value: "input",
          label: "单行文本框"
        },
        {
          value: "inputNumber",
          label: "单行纯数字(整数)"
        },
        {
          value: "inputFloat",
          label: "单行纯数字（小数）"
        },
        {
          value: "select",
          label: "单级下拉框"
        },
        {
          value: "date",
          label: "时间选择框"
        },
        {
          value: "organization",
          label: "组织架构选择框"
        }
      ],
      selectDateOptions: [
        {
          value: "minute",
          label: "分"
        },
        {
          value: "date",
          label: "天"
        },
        {
          value: "month",
          label: "月"
        },
        {
          value: "year",
          label: "年"
        }
      ],
      dialogFormVisible: false,
      loadList: false,
      tableData: constData,
      ruleForm: {
        userName: "",
        userType: "",
        enable: "",
        password: "",
        realName: "",
        phone: "",
        organId: "",
        positionsId: ""
      },
      rules: {
        userName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        realName: [
          { required: true, message: "请选择活动区域", trigger: "change" }
        ]
      },
      password: [
        {
          required: true,
          message: "密码6-20位，包含字母、数字、符号中至少两种，字母区分大小写",
          trigger: "blur"
        }
      ],
      paginationInfo: {
        sizeChange: e => {
          console.log(e);
        },
        currentChange: e => {
          this.$store.dispatch("system_field/setListSearchParams", {
            current: e
          });
          this.getList(
            Object.assign({}, this.$store.state.system_field.listSearchParams)
          );
        },
        current: 1,
        total: 10
      },
      formOptions: {
        inline: true,
        submitBtnText: "新增字段",
        showResetBtn: true,
        resetBtnText: "保存",
        searchParamsHandler: () => {
          console.log("搜索");
          const e = {
            description: "",
            fieldCode: "",
            fieldName: "",
            fieldRule: "",
            fieldRuleType: "",
            fieldType: "",
            required: "",
            tenantId: ""
          };
          this.$store.dispatch("system_field/addOneListData", e);
          // this.getList(this.$store.state.system_field.listSearchParams);
        },
        changevalue: params => {
          //   const forms=this.formOptions.forms.map(e=>{
          //      const key=e.prop
          //      e.defaultValue=params[key]
          //     return e
          //    })
          //  console.log(forms)
          // console.log(params);
          // this.$store.dispatch("system_field/setListSearchParams", params);
        },
        resetBtnCallback: () => {
          this.update();
        },
        forms: []
      },
      columns: [
        { type: "index", prop: "empno", label: "字段ID", width: 100 },

        {
          prop: "fieldName",
          label: "字段名称",
          width: 180,
          slotName: "slot-fieldName"

          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.name ? deviceInfo.name :"";
          // },
        },
        {
          prop: "fieldType",
          label: "字段类型",
          width: 180,
          slotName: "slot-fieldType"
          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.deviceNumber ? deviceInfo.deviceNumber :"";
          // },
        },
        // { prop: "departmentName", label: "使用部门", minWidth: 180, render: (row) => {
        //     const { departmentInfo } = row;
        //     return departmentInfo.name ? departmentInfo.name :"";
        //   },},
        {
          prop: "fieldRuleType",
          label: "字段规则",
          minWidth: 180,
          slotName: "slot-fieldRuleType"
        },
        {
          prop: "description",
          label: "提示语",
          minWidth: 180,
          slotName: "slot-description"
        },
        // {
        //   prop: "itemsSum",
        //   label: "点检项",
        //   slotName: "items-sum",
        //   minWidth: 180,
        // },
        {
          prop: "required",
          label: "必填/选填",
          minWidth: 180,
          slotName: "slot-required"
        },

        {
          prop: "operate",
          label: "操作",
          minWidth: 200,
          slotName: "operate-column",
          fixed: "right"
        }
      ]
    };
  },

  watch: {
    formChange: () => {}
  },
  computed: {
    ...mapState(["system_field", "app"])
  },
  created() {
    // 初始获取几个基本数据,分别为操作状态,按钮权限等
    (this.formOptions.forms = this.formOptions.forms.map(e => {
      const key = e.prop;
      const data = this.$store.state.system_field.listSearchParams;
      e.defaultValue = data[key] || "";
      return e;
    })),
      // this.submitHandler=this.searchWithParams
      this.$store
        .dispatch(this.$store_url_button, {
          add: this.add,
          export: this.export,
          delete: this.delete,
          edit: this.edit,
          detail: this.detail,
          using: this.using,
          useless: this.useless,
          downloadTemplete: this.downloadTemplete,
          downloadIdentify: this.downloadIdentify
        })
        .then(async () => {
          // await this.$store.dispatch("app/getCodeList", []); //code转码
          this.getList(); // 表格数据
        });

    // this.listQuery=this.$store.state.basicEquipment.listSearchParams||{}  //操作状态
  },
  methods: {
    moveProTableData(from, to) {
      console.log(from, "+++from+++");
      console.log(to, "++++to+++");

      const records = this.$store.state.system_field.records;
      console.log(records, "+++records++");

      // 检测移动边界
      if (to < 12 || to > records.length - 1) {
        return;
      }
      // 移动元素
      const moveTarget = records.splice(from, 1)[0];
      console.log(moveTarget, "++moveTarget+++");
      records.splice(to, 0, moveTarget);
      console.log(records, "+++after records+++");

      this.$store.dispatch("system_field/moveDeviceInfo", records);
    },

    deleteProTableData(row) {
      console.log(row, "+++++row++++");

      this.$store.dispatch("system_field/deleteDeviceInfo", row);
    },

    cancel() {
      this.dialogFormVisible = false;
    },
    dialogSubmit() {
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          console.log(valid);
          this.$store
            .dispatch("system_field/saveInfo", this.ruleForm)
            .then(res => {
              this.getList();
              this.dialogFormVisible = false;
            })
            .catch(err => {});
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 自定义该业务模块下的按钮方法
    using(row) {
      this.$store
        .dispatch("system_field/useUserInfo", row.id)
        .then(res => {
          this.getList();
          // this.dialogFormVisible=false
        })
        .catch(err => {});
    },
    useless(row) {
      this.$store
        .dispatch("system_field/uselessUserInfo", row.id)
        .then(res => {
          this.getList();
          // this.dialogFormVisible=false
        })
        .catch(err => {});
    },
    add(row) {
      console.log(row);
      this.dialogFormVisible = true;
    },
    edit(row) {
      this.ruleForm = row;
      this.dialogFormVisible = true;
    },
    downloadIdentify(row) {
      console.log("下载设备标识卡");
      this.dialogFormVisible = true;
    },
    async downloadTemplete(ids) {
      console.log("下载导出模板");
      const download = await this.$store.dispatch(
        "system_field/downloadTemplete"
      );
      // window.open(download.)
      console.log(download);
    },
    delete(row) {
      console.log(row);
      this.$store.dispatch("system_field/deleteDeviceInfo", row); // 前端删除
    },
    update() {
      // 直接由vuex处理
      this.$store
        .dispatch("system_field/saveInfo")
        .then(res => {
          console.log(res, "+++res+++");
          this.getList();
        })
        .catch(err => {
          console.log(err);
        });
    },
    detail(row) {
      console.log(row);

      localStorage.setItem("/device-basic/component/detail/index", row.id);
      this.$router.push("/device-basic/component/detail/index");
    },
    import() {},
    export() {
      console.log("导出");
      this.$store.dispatch("system_field/exportFile");
    },
    // 弹窗的关闭
    cancel() {
      console.log("关闭弹窗");
      this.dialogFormVisible = false;
    },
    // 更新弹窗数据
    updateDialog() {
      console.log("更新并关闭弹窗");
      this.dialogFormVisible = false;
    },
    // 搜索按钮
    searchWithParams() {
      console.log("搜索");
    },
    getList(args) {
      this.$store
        .dispatch("system_field/requestFieldList", args)
        .then(
          this.$set(this, "tableData", this.$store.state.system_field.records)
        );
    },
    handleFilter(args) {
      this.listQuery.page = 1;
      this.getList(args);
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: "操作成功",
        type: "success"
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        status: "published",
        type: ""
      };
    },
    handleCreate() {
      // this.resetTemp();
      // this.dialogStatus = "create";
      // this.dialogFormVisible = true;
      // this.$nextTick(() => {
      //   this.$refs["dataForm"].clearValidate();
      // });
      this.dialogFormVisible = true;
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleDelete(row) {
      this.$notify({
        title: "成功",
        message: "删除成功",
        type: "success",
        duration: 2000
      });
      const index = this.list.indexOf(row);
      this.list.splice(index, 1);
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    }
  }
};
</script>
<style scoped>
.input-selected input.el-input__inner {
  border: 2px solid red;
}
</style>
